package servlet;

import dao.CategoryDao;
import dao.LabelDao;
import dao.UserDao;
import dao.daoimpl.CategoryDaoImpl;
import dao.daoimpl.LabelDaoImpl;
import dao.daoimpl.UserDaoImpl;
import bean.Category;
import bean.Label;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//注册账号服务器
@WebServlet(name="RegisterServlet",urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        String account=request.getParameter("userAccount");/*获取账号*/
        String password=request.getParameter("userPassword");/*获取密码*/
        String code1=request.getParameter("userSecurityCode");/*获取验证码*/
        String qqEmail=account;/*邮箱*/
        User user=new User(account,password,qqEmail,0);/*普通用户注册，标记0*/
        String code2=null;
        Cookie []cookies=request.getCookies();/*获取验证码*/
        for(Cookie cookie1:cookies){
            if("code".equals(cookie1.getName())){
                code2=cookie1.getValue();
            }
        }
        UserDao userDao=new UserDaoImpl();
        CategoryDao categoryDao=new CategoryDaoImpl();
        LabelDao labelDao=new LabelDaoImpl();
        String time= new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());/*获取当前时间*/
        if(code1.equals(code2)){/*核实输入的验证码与系统生成的验证码是否一致*/
            if(userDao.register(user)&&categoryDao.addCategory(new Category("默认",time,user.getAccount(),"系统默认分栏"))&&labelDao.addLabel(new Label("java",time,user.getAccount()))) {/*进行注册*/
                request.setAttribute("account", account);/*传回账号方便登录*/
                request.getRequestDispatcher("loginPage.jsp").forward(request, response);//跳转到登录页面
            }else{
                request.setAttribute("fail","注册失败，请稍后重试");/*失败*/
            }
        }else{
            request.setAttribute("error","验证码错误");/*验证码输入有误*/
            request.getRequestDispatcher("registerPage.jsp").forward(request,response);/*重新注册*/
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

}
